package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleCollectionService;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.UpdateArticleInfo;
import com.heima.model.behavior.dtos.CollectionBehaviorDto;
import com.heima.model.behavior.pojos.UserBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author HNCheng
 * @version 1.0
 * @since 2023/8/2 22:48
 */
@Service
public class ArticleCollectionServiceImpl implements ArticleCollectionService {
    @Autowired
    private CacheService cacheService;
    @Autowired
    private ApArticleService apArticleService;

    /**
     * 文章收藏
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
        //1.校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.获取当前用户
        ApUser user = ApUserThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.根据key从缓存中获取UserBehavior对象
        String json = (String) cacheService.hGet(user.getId().toString(), dto.getEntryId().toString());

        UserBehavior userBehavior = new UserBehavior();
        if (StringUtils.isNotBlank(json)) {
            userBehavior = JSON.parseObject(json, UserBehavior.class);
        }

        //更新文章信息
        UpdateArticleInfo articleInfo = new UpdateArticleInfo();
        articleInfo.setArticleId(dto.getEntryId());
        if (dto.getOperation() == 0) {
            //收藏数+1
            userBehavior.setIsCollection(true);
            articleInfo.setCollection(1);
        } else {
            //收藏数-1
            userBehavior.setIsCollection(false);
            articleInfo.setCollection(-1);
        }

        //更新收藏
        cacheService.hPut(user.getId().toString(), dto.getEntryId().toString(), JSON.toJSONString(userBehavior));

        //更新数据库中ap_article表信息
        apArticleService.updateArticleInfo(articleInfo);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
